import request from './request.js'

// const baseUrl = 'https://api.kuaimayoupin.com/huipaysns/mitang/'
const baseUrl = 'https://api.sweetketang.com/'
// const baseUrl = 'http://47.94.169.143:8005/'
// const baseUrl ='http://127.0.0.1:7001/';
// const baseUrl ='http://127.0.0.1:8005/';
// const baseUrl = 'http://39.107.226.251:8005/';
request.setConfig({
    baseUrl: baseUrl,
    debug: true
})

// 请求拦截
request.interceptor.request = (config => {
    try {
        const token = uni.getStorageSync('token');
		// const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiI1N2I3NzM3MC0wODZkLTExZWItODYzYS00Zjc3YjM0MDQ3ZDQiLCJpYXQiOjE2MTA3MjI0ODN9.C9YOy0ZxE1nkzTEjXqKOx79KHLPAt0Ld1mf1okW3F8U';
        if (token) {
            config.header.token = token;
        }
    } catch (e) {
        // error
    }
    // 添加一个自定义的参数，默认异常请求都弹出一个toast提示
    if (config.toastError === undefined) {
        config.toastError = true
    }
    return config;
})

// 全局的业务拦截
request.interceptor.response = ((res, config) => {
	if(res.status===0){
		uni.showToast({
		    title: res.message,
		    duration: 2000,
		    icon: 'none'
		})
	}
    if (res.status === 1) {
        res.success = true;
    }
	if (res.errcode === 10) {
	    // token失效，需要重新登录
		try{
			uni.removeStorageSync('userInfo');
		}catch(e){
			//TODO handle the exception
		}
	}
    return res;
})

const ignoreCodes = [500201,500120];

// 全局的错误异常处理
request.interceptor.fail = ((res, config) => {
    let ret = res;
    let msg = ''
    if (res.statusCode === 200) { // 业务错误
        msg = res.data.errmsg
        ret = res.data
    } else if (res.statusCode > 0) { // HTTP错误
        msg = '服务器异常[' + res.statusCode + ']'
    } else { // 其它错误
        msg = res.errMsg
    }
	let errordata =  res.data || {}
	let errorcode = errordata.errcode || -100
    if (config.toastError) {
			if(ignoreCodes.includes(errorcode)){
				return ret;
			}
    }
    return ret;
})

export {request};
